# coding=utf-8
import Queue, traceback, json
from flask_socketio import Namespace, emit
from app.extensions import log
from app.modules.common.utils import ComplexEncoder

thread = None
NAMESPACE = '/notify'
EVENT = 'stat'
send_queue = Queue.Queue()


def send_message(data):
    from .models import NotifyModel
    if isinstance(data, NotifyModel):
        try:
            send_queue.put(data, block = True, timeout = 10)
        except:
            log.error(u"Notifer消息入队失败!")
            log.error(traceback.format_exc())
    else:
        log.error(u"Notifer消息格式错误!")


def background_thread(socketio):
    while True:
        socketio.sleep(0.1)
        data = None
        event = None
        try:
            data = send_queue.get(block = False)
            event = data.event
            data = json.dumps(data.data, encoding = "UTF-8", ensure_ascii = False, cls = ComplexEncoder)
            log.info("send data:" + data + ";event:" + event)
            socketio.emit(event,
                          {'data': data},
                          namespace = NAMESPACE)
        except Queue.Empty:
            continue
        except:
            log.warn(u"Notifer发送消息错误.")
            log.error(traceback.format_exc())


class NotifierNamespace(Namespace):
    def __init__(self):
        super(NotifierNamespace, self).__init__(namespace = NAMESPACE)

    def on_my_ping(self):
        emit('my_pong')

    def on_connect(self):
        global thread
        if thread is None:
            thread = self.socketio.start_background_task(background_thread, self.socketio)
        emit(EVENT, {'data': 'Connected'})
